﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public enum PopupKind
{
    Popup_Goal,
    Popup_IngameRanking,
    Popup_Levelup,
    Popup_DailyMissionList,
    Popup_DailyAttendanceCheck,
    Max
}

public class PopupManager : MonoBehaviour
{

    static PopupManager instance;
    const string prefabPath = "Prefabs/Popup/PopupRoot";
    const float AniTime = 1.0f;

    public Camera m_Cam;
    Camera m_RootCam = null;
    public UICamera m_UIcam;
    public GameObject m_LetterBox;

    static public PopupManager Instance
    {
        get
        {
            if (instance == null)
            {
                GameObject obj = Resources.Load(prefabPath) as GameObject;
                obj = Instantiate(obj) as GameObject;
                obj.name = "PopupManagerWithRoot";
                DontDestroyOnLoad(obj);
                obj.transform.position = new Vector3(2000, 0, 0);

                instance = obj.GetComponent<PopupManager>();
                instance.m_AnchorTr = obj.transform.FindChild("Camera").FindChild("Anchor");
            }
            return instance;
        }

        set { instance = value; }
    }

    void Awake()
    {
        gameObject.name = "PopupManagerWithRoot";
        DontDestroyOnLoad(gameObject);
        gameObject.transform.position = new Vector3(200000, 0, 0);

        instance = gameObject.GetComponent<PopupManager>();
        instance.m_AnchorTr = gameObject.transform.FindChild("Camera").FindChild("Anchor");
    }

    static public List<GameObject> popups = new List<GameObject>();
    const int DefaultDepth = 0;

    //매니져 멤버 변수
    Transform m_AnchorTr = null;

    static public Popup PopupPush(PopupKind kindOfPopup)
    {
        return Instance.Push(kindOfPopup);
    }

    static public void PopupPop()
    {
        Instance.Pop();
    }

    static public void PopupPop(GameObject obj)
    {
        Instance.Pop(obj);
    }

    Popup Push(PopupKind kindOfPopup)
    {
        GameObject popupPrefab = null;
        popupPrefab = Resources.Load(string.Format("Prefabs/Popup/{0}", kindOfPopup)) as GameObject;

        GameObject popObj = Instantiate(popupPrefab) as GameObject;
        popups.Add(popObj);

        SetAllChildTransformLayer(popObj.transform, LayerMask.NameToLayer("Popup"));  //레이어를 팝업으로 바꿈

        RenderSortingOrderSetting rsos = popObj.AddComponent<RenderSortingOrderSetting>();  // 소팅 렌더 컨트롤 FX보다 위로 올수있도록
        rsos.isNeedChildControl = true;
        rsos.LayerName = "Popup";

        popObj.transform.parent = m_AnchorTr;
        popObj.transform.localScale = Vector3.one;
        popObj.transform.localPosition = Vector3.zero;

        Popup sc = popObj.GetComponent(kindOfPopup.ToString()) as Popup;

        UIPanel m_UIPanel = popObj.GetComponent<UIPanel>();
        if (m_UIPanel == null)
            m_UIPanel = popObj.AddComponent<UIPanel>();

        m_UIPanel.depth = DefaultDepth + popups.Count;



        GameObject body = popObj.transform.FindChild("Body").gameObject;
        body.transform.localScale = Vector3.one / 10;
        iTween.ScaleTo(body, iTween.Hash("easetype", "spring", "islocal", true, "time", 0.5f, "scale", Vector3.one));//, "oncompletetarget", popObj, "oncomplete", "Showcomplte"));

        GameObject BG = popObj.transform.FindChild("BG").gameObject;
        BG.SetActive(true);
        ////팝업 배경 애니메이션
        //TweenAlpha ta = BG.GetComponent<TweenAlpha>();
        //if (ta == null)
        //    ta = BG.AddComponent<TweenAlpha>();

        //ta.from = 0.0f;
        //ta.to = 1.0f;
        //ta.ignoreTimeScale = true;
        //ta.style = UITweener.Style.Once;
        //ta.duration = AniTime;
        //ta.Play(true);

        return sc;
    }

    void Pop()   // 여러개 팝업중 제일 위에 팝업 삭제
    {
        if (popups.Count > 0)
        {
            GameObject PopObj = popups[popups.Count - 1];
            if (PopObj != null)
            {
                popups.Remove(PopObj);

                GameObject body = PopObj.transform.FindChild("Body").gameObject;
                iTween.ScaleTo(body, iTween.Hash("easetype", "spring", "islocal", true, "time", 0.5f, "scale", Vector3.zero, "oncompletetarget", gameObject, "oncomplete", "EndShow", "oncompleteparams", PopObj));

                GameObject BG = PopObj.transform.FindChild("BG").gameObject;
                BG.SetActive(false);

                ////팝업 배경 애니메이션
                //TweenAlpha ta = BG.GetComponent<TweenAlpha>();
                //if (ta == null)
                //    ta = BG.AddComponent<TweenAlpha>();

                //ta.from = 0.0f;
                //ta.to = 1.0f;
                //ta.ignoreTimeScale = true;
                //ta.style = UITweener.Style.Once;
                //ta.duration = AniTime;
                //ta.Play(false);
            }
        }
    }

    void Pop(GameObject popup)   // 여러개 팝업중 제일 위에 팝업 삭제
    {
        GameObject PopObj = popup;
        if (PopObj != null)
        {
            if (popups.Contains(PopObj))
                popups.Remove(PopObj);

            GameObject body = PopObj.transform.FindChild("Body").gameObject;
            iTween.ScaleTo(body, iTween.Hash("easetype", "spring", "islocal", true, "time", 0.5f, "scale", Vector3.zero, "oncompletetarget", gameObject, "oncomplete", "EndShow", "oncompleteparams", PopObj));

            GameObject BG = PopObj.transform.FindChild("BG").gameObject;
            BG.SetActive(false);

            ////팝업 배경 애니메이션
            //TweenAlpha ta = BG.GetComponent<TweenAlpha>();
            //if (ta == null)
            //    ta = BG.AddComponent<TweenAlpha>();

            //ta.from = 0.0f;
            //ta.to = 1.0f;
            //ta.ignoreTimeScale = true;
            //ta.style = UITweener.Style.Once;
            //ta.duration = AniTime;
            //ta.Play(false);            
        }
    }

    void EndShow(GameObject PopObj)
    {
        //m_Cam.enabled = (popups.Count > 0);
        Destroy(PopObj);
    }

    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            Pop();
        }

        if (isCompleteLoad)
        {
            if (m_RootCam == null)
            {
                SetPos(true);
            }
            else if (m_Cam.orthographicSize != m_RootCam.orthographicSize)
                SetPos(true);
        }

        if (popups.Count > 0 && !m_UIcam.enabled)
        {
            m_UIcam.enabled = true;
        }
    }


    static public void SetPopupBeforeLevelLoad()    // 씬 변경시 호출
    {
        Instance.SetPos(false);
    }


    void OnLevelWasLoaded()     // 게임씬 전환시 구동
    {
        SetPos(true);
    }

    bool isCompleteLoad = true;
    void SetPos(bool isSet)     // 포지션 설정
    {
        if (isSet)
        {
            isCompleteLoad = true;
            Transform uiRoot = GameObject.Find("UI Root (2D)").transform;

            transform.parent = uiRoot;
            transform.localPosition = new Vector3(200000, 0, 0);
            transform.localScale = Vector3.one;
            transform.parent = null;
            m_RootCam = uiRoot.FindChild("Camera").camera;
            m_Cam.orthographicSize = m_RootCam.orthographicSize;

            if (CSceneManager.m_Scene == SCENE.InGameScene || CSceneManager.m_Scene == SCENE.SummonCommonScene)
                m_LetterBox.SetActive(false);
            else
                m_LetterBox.SetActive(true);
        }
        else
        {
            isCompleteLoad = false;
            transform.parent = null;
        }
    }

    void SetAllChildTransformLayer(Transform t, int layerIndex)
    {
        t.gameObject.layer = layerIndex;

        foreach (Transform child in t)
        {
            SetAllChildTransformLayer(child, layerIndex);
        }
    }

    IEnumerator DestroyWithDelay(GameObject obj, float time)
    {
        yield return new WaitForSeconds(time);
        Destroy(obj);
    }
}
